import { UITransform, _decorator } from 'cc'
import { EntityManager } from '../../Base/EntityManager'
import { IEntity } from '../../Levels'
import EventManager from '../../Runtime/EventManager'
import { ENTITY_STATE_ENUM, EVENT_ENUM, SHAKE_TYPE_ENUM } from '../../Enum'
import DataManager from '../../Runtime/DataManager'
import { BurstStateMachine } from './BurstStateMachine'
import { TILE_HEIGHT, TILE_WIDTH } from '../Tile/TileManager'

const { ccclass, property } = _decorator

/**
 * Predefined variables
 * Name = BurstManager
 * DateTime = Fri Jul 22 2022 14:31:09 GMT+0800 (中国标准时间)
 * Author = Zero_Y
 * FileBasename = BurstManager.ts
 * FileBasenameNoExtension = BurstManager
 * URL = db://assets/Scripts/Burst/BurstManager.ts
 * ManualUrl = https://docs.cocos.com/creator/3.4/manual/zh/
 *
 */

@ccclass('BurstManager')
export class BurstManager extends EntityManager {
  async init(params: IEntity) {
    this.fsm = this.addComponent(BurstStateMachine)
    await this.fsm.init()
    super.init(params)
    //重写大小，设置为占一格
    const transform = this.getComponent(UITransform)
    transform.setContentSize(TILE_WIDTH, TILE_HEIGHT)
    EventManager.Instance.on(EVENT_ENUM.PLAYER_MOVE_END, this.onBurst, this)
  }

  // 解绑事件
  onDestroy() {
    super.onDestroy()
    EventManager.Instance.off(EVENT_ENUM.PLAYER_MOVE_END, this.onBurst)
  }

  // 重写update，因为只占1格
  update() {
    this.node.setPosition(this.x * TILE_WIDTH, -this.y * TILE_HEIGHT)
  }

  // 地裂
  onBurst() {
    if (this.state === ENTITY_STATE_ENUM.DEATH || !DataManager.Instance.player) {
      return
    }
    const { x: playX, y: playY } = DataManager.Instance.player
    if (this.x === playX && this.y === playY && this.state === ENTITY_STATE_ENUM.IDLE) {
      this.state = ENTITY_STATE_ENUM.ATTACK
    } else if (this.state === ENTITY_STATE_ENUM.ATTACK) {
      // 地裂消失
      this.state = ENTITY_STATE_ENUM.DEATH
      // 震动
      EventManager.Instance.emit(EVENT_ENUM.SCREEN_SHAKE, SHAKE_TYPE_ENUM.BOTTOM)
      if (this.x === playX && this.y === playY) {
        // 如果地裂消失之后玩家还在当前位置，玩家空中死亡
        EventManager.Instance.emit(EVENT_ENUM.ATTACK_PLAYER, ENTITY_STATE_ENUM.AIRDEATH)
      }
    }
  }
}
